from threading import Thread, RLock
from queue import Queue
import time

q = Queue(10)
count = 0
l = RLock()


# 创建生产者
class Producer(Thread):
    def __init__(self, name, que):
        super(Producer, self).__init__()
        # Thread.__init__(self)
        self._name = name
        self._que = que

    def run(self): # 重写run方法
        while True:
            global count
            l.acquire()
            count += 1
            l.release()
            self._que.put(count)
            print('{} produce {}'.format(self._name, count))
            time.sleep(0.5)
            self._que.join() # 没看懂


# 创建消费者
class Consumer(Thread):
    def __init__(self, name, que):
        Thread.__init__(self)
        self._name = name
        self._que = que

    def run(self):
        while True:
            data = self._que.get()
            print('{} eat {}'.format(self._name, data))
            time.sleep(1)
            self._que.task_done()


def main():
    p1 = Producer('writer', q)
    c1 = Consumer('chen', q)
    c2 = Consumer('ming', q)
    c3 = Consumer('nan', q)
    p1.start()
    c1.start()
    c2.start()
    c3.start()

if __name__ == "__main__":
    main()